package com.ledong.designPatten.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxy {
    public static void main(String[] args) throws Exception {
        Job job = JobFactory.getJob();
        job.code();
    }
}

interface Job {
    public void code();
}

class Worker implements Job {
    public void code() {
        System.out.println("worker code");
    }

    public void play() {
        System.out.println("worker play");
    }
}

class Handler implements InvocationHandler {
    private Worker worker;

    public Handler(Worker worker) {
        this.worker = worker;
    }

    public Object invoke(Object obj, Method mtd, Object[] objs)
            throws Throwable {
        Object res = null;
        System.out.println("check permission");
        res = mtd.invoke(worker, objs);
        System.out.println("get the saraly");
        return res;
    }
}

class JobFactory {
    public static Job getJob() {
        Worker worker = new Worker(); // 这是代理，可以代理接口指定的工作
        if (!(worker instanceof Job))// 判断是否有资格当这些工作的代理
            return null;
        /* construct a invocation handler with the impl instance */
        InvocationHandler handler = new Handler(worker); // 这是实际工作的人
        /* get the class info, and the class loader used by this factory */
        Class[] interfaces = new Class[] { Job.class };
        ClassLoader loader = JobFactory.class.getClassLoader();
        Job proxy = (Job) Proxy.newProxyInstance(loader, interfaces, handler);
        return proxy;
    }
}